package com.yc.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.services.OrdersQueryVO;
import com.yc.services.OrdersService;
import com.yc.web.DTO.OrdersDTO;
import com.yc.web.controller.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 创建订单
     * POST /orders/create
     * @param ordersDTO 订单信息
     * @return 包含订单信息的统一响应
     */
    @PostMapping("/create")
    public ResponseEntity<ResponseResult> createOrder(@RequestBody OrdersDTO ordersDTO) {
        try {
            OrdersDTO createdOrder = ordersService.createOrder(ordersDTO);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ResponseResult.ok("订单创建成功").setData(createdOrder));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("订单创建失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户ID和状态查询订单
     * GET /orders/list
     * @param userId 用户ID
     * @param status 订单状态(可选)
     * @return 包含订单列表的统一响应
     */
    @GetMapping("/list")
    public ResponseEntity<ResponseResult> getOrdersByUserAndStatus(
            @RequestParam Long userId,
            @RequestParam(required = false) Integer status) {
        try {
            List<OrdersDTO> orders = ordersService.getOrdersByUserAndStatus(userId, status);
            return ResponseEntity.ok(ResponseResult.ok("查询订单成功").setData(orders));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询订单失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询订单
     * GET /orders/page
     * @param queryVO 查询参数
     * @return 包含订单分页结果的统一响应
     */
    @GetMapping("/page")
    public ResponseEntity<ResponseResult> getOrdersPaged(@RequestBody OrdersQueryVO queryVO) {
        try {
            IPage<OrdersDTO> ordersPage = ordersService.listOrdersPaged(queryVO);
            return ResponseEntity.ok(ResponseResult.ok("查询订单成功").setData(ordersPage));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询订单失败: " + e.getMessage()));
        }
    }

//    查询示例
//    这个实现支持以下查询方式：
//    基本查询：
//    /orders/page?userId=123 - 查询用户123的所有订单
//    /orders/page?userId=123&orderStatus=2 - 查询用户123的已支付待发货订单
//    分页控制：
//    /orders/page?userId=123&current=2&size=20 - 查询用户123的订单，第2页，每页20条
//    排序控制：
//    /orders/page?userId=123&sortField=paymentTime&sortOrder=desc - 按支付时间降序排列
//    /orders/page?userId=123&sortField=updateTime - 按更新时间升序排列(默认)
//    时间范围查询：
//    /orders/page?userId=123&startTime=2023-01-01T00:00:00&endTime=2023-12-31T23:59:59 - 查询2023年的订单
//    这个实现提供了灵活的分页查询功能，可以根据需要扩展更多的查询条件。

    /**
     * 获取订单详情
     * GET /product/orders/detail/{orderId}
     * @param orderId 订单ID
     * @return 包含订单详情的统一响应
     */
    @GetMapping("/detail/{orderId}")
    public ResponseEntity<ResponseResult> getOrderDetail(@PathVariable Long orderId) {
        try {
            OrdersDTO orderDetail = ordersService.getOrderDetail(orderId);
            return ResponseEntity.ok(ResponseResult.ok("查询订单详情成功").setData(orderDetail));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询订单详情失败: " + e.getMessage()));
        }
    }

    /**
     * 取消订单
     * POST /product/orders/cancel/{orderId}
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/cancel/{orderId}")
    public ResponseEntity<ResponseResult> cancelOrder(@PathVariable Long orderId) {
        try {
            boolean result = ordersService.cancelOrder(orderId);
            if (result) {
                return ResponseEntity.ok(ResponseResult.ok("订单取消成功"));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("订单取消失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("订单取消失败: " + e.getMessage()));
        }
    }

    /**
     * 确认收货
     * POST /product/orders/confirm/{orderId}
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/confirm/{orderId}")
    public ResponseEntity<ResponseResult> confirmReceipt(@PathVariable Long orderId) {
        try {
            boolean result = ordersService.confirmReceipt(orderId);
            if (result) {
                return ResponseEntity.ok(ResponseResult.ok("确认收货成功"));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("确认收货失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("确认收货失败: " + e.getMessage()));
        }
    }

    /**
     * 申请售后
     * POST /product/orders/after-sale
     * @param orderId 订单ID
     * @param reason 售后原因
     * @return 操作结果
     */
    @PostMapping("/after-sale")
    public ResponseEntity<ResponseResult> applyAfterSale(
            @RequestParam Long orderId,
            @RequestParam String reason) {
        try {
            boolean result = ordersService.applyAfterSale(orderId, reason);
            if (result) {
                return ResponseEntity.ok(ResponseResult.ok("售后申请已提交"));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("售后申请失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("售后申请失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户订单各状态数量统计
     * GET /orders/status-counts
     * @param userId 用户ID
     * @return 包含订单统计的统一响应
     */
    @GetMapping("/status-counts")
    public ResponseEntity<ResponseResult> getOrderStatusCounts(
            @RequestParam Long userId) {
        try {
            Map<Integer, Long> counts = ordersService.getOrderStatusCounts(userId);

            // 转换为前端需要的格式
            Map<String, Long> formattedCounts = new HashMap<>();
            formattedCounts.put("pendingPayment", counts.getOrDefault(1, 0L));   // 待支付
            formattedCounts.put("pendingShipment", counts.getOrDefault(2, 0L)); // 待发货
            formattedCounts.put("pendingReceipt", counts.getOrDefault(3, 0L));  // 待收货
            formattedCounts.put("pendingReview", counts.getOrDefault(4, 0L));   // 待评价
            formattedCounts.put("afterSale", counts.getOrDefault(6, 0L));      // 退款/售后

            return ResponseEntity.ok(ResponseResult.ok("查询订单统计成功").setData(formattedCounts));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询订单统计失败: " + e.getMessage()));
        }
    }

    /**
     * 更新订单状态
     * PUT /orders/status
     * @param orderId 订单ID
     * @param newStatus 新状态
     * @return 操作结果
     */
    @PutMapping("/status")
    public ResponseEntity<ResponseResult> updateOrderStatus(
            @RequestParam Long orderId,
            @RequestParam Integer newStatus) {
        try {
            boolean result = ordersService.updateOrderStatus(orderId, newStatus);
            if (result) {
                return ResponseEntity.ok(ResponseResult.ok("订单状态更新成功"));
            }
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("订单状态更新失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("订单状态更新失败: " + e.getMessage()));
        }
    }
}